<template>
  <el-scrollbar class="side-scroll-bar">
    <div class="panel-container">

      <el-tabs v-model="firstTab" class="no-bottom-margin indent-left-margin">

        <el-tab-pane v-if="showChartLib" name="chartLib">
          <template #label>
            <span><svg-icon icon-class="el-chart"/> {{ i18nt('designer.chartLib') }}</span>
          </template>

          <el-collapse v-model="activeNames" class="widget-collapse">
            <el-collapse-item name="1" :title="i18nt('designer.containerTitle')">
              <!-- 图表组件不支持拖拽添加到画布，必须鼠标双击添加！！ -->
              <draggable tag="ul" :list="chartContainers" item-key="key"
                         :group="{name: 'dragGroup', pull: 'clone', put: false}"
                         :clone="handleContainerWidgetClone" ghost-class="ghost" :sort="false" :disabled="true"
                         :move="checkContainerMove" @end="onContainerDragEnd">
                <template #item="{ element: ctn }">
                  <li class="chart-container-widget-item" :title="ctn.displayName"
                      @dblclick="addChartContainerByDbClick(ctn)">
                    <span><svg-icon :icon-class="ctn.icon" class-name="color-svg-icon"/>{{ getWidgetLabel(ctn) }}</span>
                  </li>
                </template>
              </draggable>
            </el-collapse-item>

            <el-collapse-item name="2" :title="i18nt('designer.chartTitle')">
              <!-- 图表组件不支持拖拽添加到画布，必须鼠标双击添加！！ -->
              <draggable tag="ul" :list="chartWidgets" item-key="key"
                         :group="{name: 'dragGroup', pull: 'clone', put: false}"
                         :move="checkFieldMove" :disabled="true"
                         :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
                <template #item="{ element: chart }">
                  <li class="chart-widget-item" :title="chart.displayName" @dblclick="addChartByDbClick(chart)">
                    <div class="svg-icon-label">
                      <svg-icon :icon-class="chart.icon" class-name="color-svg-icon"/>
                      <span class="chart-widget-item__label">{{ getWidgetLabel(chart) }}</span>
                    </div>
                  </li>
                </template>
              </draggable>
            </el-collapse-item>
          </el-collapse>

        </el-tab-pane>

        <el-tab-pane v-if="showMetadataLib" name="metadataLib">
          <template #label>
            <span><svg-icon icon-class="el-module"/> {{ i18nt('designer.metadataLib') }}</span>
          </template>

          <el-collapse v-model="metadataActiveNames" class="widget-collapse">
            <el-collapse-item name="0" :title="i18nt('designer.containerTitle')">
              <draggable tag="ul" :list="commonContainers" item-key="key"
                         :group="{name: 'dragGroup', pull: 'clone', put: false}"
                         :clone="handleContainerWidgetClone" ghost-class="ghost" :sort="false"
                         :move="checkContainerMove" @end="onContainerDragEnd">
                <template #item="{ element: ctn }">
                  <li class="container-widget-item" :title="ctn.displayName" @dblclick="addContainerByDbClick(ctn)">
                    <span><svg-icon :icon-class="ctn.icon" class-name="color-svg-icon"/>{{ getWidgetLabel(ctn) }}</span>
                  </li>
                </template>
              </draggable>
            </el-collapse-item>

            <template v-if="metaFields.main.entityName">
              <el-collapse-item name="1" :title="metaFields.main.entityLabel">
                <draggable tag="ul" :list="metaFields.main.fieldList" item-key="key"
                           :group="{name: 'dragGroup', pull: 'clone', put: false}"
                           :move="checkFieldMove"
                           :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
                  <template #item="{ element: fld }">
                    <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                      <span><svg-icon :icon-class="fld.icon"
                                      class-name="color-svg-icon"/>{{ getMetaFieldLabel(fld) }}</span>
                    </li>
                  </template>
                </draggable>
              </el-collapse-item>
            </template>

            <template v-if="metaFields.detail && (metaFields.detail.length > 0)">
              <template v-for="(de, index) in metaFields.detail">
                <el-collapse-item name="index + 2 + ''" :title="de.entityLabel">
                  <draggable tag="ul" :list="de.fieldList" item-key="key"
                             :group="{name: 'dragGroup', pull: 'clone', put: false}"
                             :move="checkFieldMove"
                             :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
                    <template #item="{ element: fld }">
                      <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                        <span><svg-icon :icon-class="fld.icon" class-name="color-svg-icon"/>{{ getMetaFieldLabel(fld) }}</span>
                      </li>
                    </template>
                  </draggable>
                </el-collapse-item>
              </template>
            </template>
          </el-collapse>
        </el-tab-pane>

        <el-tab-pane v-if="showComponentLib" name="componentLib">
          <template #label>
            <span><svg-icon icon-class="el-set-up"/> {{ i18nt('designer.componentLib') }}</span>
          </template>

          <el-collapse v-model="activeNames" class="widget-collapse">
            <el-collapse-item name="1" :title="i18nt('designer.containerTitle')">
              <draggable tag="ul" :list="containers" item-key="key"
                         :group="{name: 'dragGroup', pull: 'clone', put: false}"
                         :clone="handleContainerWidgetClone" ghost-class="ghost" :sort="false"
                         :move="checkContainerMove" @end="onContainerDragEnd">
                <template #item="{ element: ctn }">
                  <li class="container-widget-item" :title="ctn.displayName" @dblclick="addContainerByDbClick(ctn)">
                    <span><svg-icon :icon-class="ctn.icon" class-name="color-svg-icon"/>{{ getWidgetLabel(ctn) }}</span>
                  </li>
                </template>
              </draggable>
            </el-collapse-item>

            <el-collapse-item name="2" :title="i18nt('designer.basicFieldTitle')">
              <draggable tag="ul" :list="basicFields" item-key="key"
                         :group="{name: 'dragGroup', pull: 'clone', put: false}"
                         :move="checkFieldMove"
                         :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
                <template #item="{ element: fld }">
                  <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                    <span><svg-icon :icon-class="fld.icon" class-name="color-svg-icon"/>{{ getWidgetLabel(fld) }}</span>
                  </li>
                </template>
              </draggable>
            </el-collapse-item>

            <el-collapse-item name="3" :title="i18nt('designer.advancedFieldTitle')">
              <draggable tag="ul" :list="advancedFields" item-key="key"
                         :group="{name: 'dragGroup', pull: 'clone', put: false}"
                         :move="checkFieldMove"
                         :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
                <template #item="{ element: fld }">
                  <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                    <span><svg-icon :icon-class="fld.icon" class-name="color-svg-icon"/>{{ getWidgetLabel(fld) }}</span>
                  </li>
                </template>
              </draggable>
            </el-collapse-item>

            <el-collapse-item name="4" :title="i18nt('designer.customFieldTitle')">
              <draggable tag="ul" :list="customFields" item-key="key"
                         :group="{name: 'dragGroup', pull: 'clone', put: false}"
                         :move="checkFieldMove"
                         :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
                <template #item="{ element: fld }">
                  <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                  <span>
                    <svg-icon :icon-class="fld.icon" class-name="color-svg-icon"/>{{ getWidgetLabel(fld) }}</span>
                  </li>
                </template>
              </draggable>
            </el-collapse-item>

          </el-collapse>

        </el-tab-pane>

        <el-tab-pane v-if="showFormTemplates" name="formLib" style="padding: 8px">
          <template #label>
            <span><svg-icon icon-class="el-form-template"/> {{ i18nt('designer.formLib') }}</span>
          </template>

          <template v-for="(ft, idx) in formTemplates">
            <el-card :bord-style="{ padding: '0' }" shadow="hover" class="ft-card">
              <el-popover placement="right" trigger="hover" popper-class="image-popover">
                <template #reference>
                  <img :src="ft.imgUrl" style="width: 200px">
                </template>
                <img :src="ft.imgUrl" style="height: 600px;width: 720px">
              </el-popover>
              <div class="bottom clear-fix">
                <span class="ft-title">#{{ idx + 1 }} {{ getFTTitle(ft) }}</span>
                <el-button link type="primary" class="right-button" @click="loadFormTemplate(ft.jsonUrl, ft.jsonStr)">
                  {{ i18nt('designer.hint.loadFormTemplate') }}
                </el-button>
              </div>
            </el-card>
          </template>
        </el-tab-pane>

      </el-tabs>

    </div>
  </el-scrollbar>
</template>

<script>
import SvgIcon from '@/components/svg-icon'
import {
  containers as CONS, basicFields as BFS, advancedFields as AFS, customFields as CFS, chartContainers as CHART_CONS,
  chartWidgets as CWS
} from "./widgetsConfig"
import {formTemplates} from './templatesConfig'
import {addWindowResizeHandler, generateId} from "@/utils/util"
import i18n, {getLocale} from "@/utils/i18n"
import axios from 'axios'

// import ftImg1 from '@/assets/ft-images/t1.png'
// import ftImg2 from '@/assets/ft-images/t2.png'
// import ftImg3 from '@/assets/ft-images/t3.png'
// import ftImg4 from '@/assets/ft-images/t4.png'
// import ftImg5 from '@/assets/ft-images/t5.png'
// import ftImg6 from '@/assets/ft-images/t6.png'
// import ftImg7 from '@/assets/ft-images/t7.png'
// import ftImg8 from '@/assets/ft-images/t8.png'

export default {
  name: "FieldPanel",
  mixins: [i18n],
  components: {
    SvgIcon
  },
  props: {
    designer: Object,
  },
  inject: ['getBannedWidgets', 'getDesignerConfig'],
  data() {
    return {
      designerConfig: this.getDesignerConfig(),

      firstTab: 'componentLib',
      activeNames: ['1', '2', '3', '4'],
      metadataActiveNames: ['0', '1', '2', '3', '4'],

      containers: [],
      commonContainers: [],
      basicFields: [],
      advancedFields: [],
      customFields: [],
      chartContainers: [],
      chartWidgets: [],

      metaFields: {
        main: {
          entityName: '',
          entityLabel: '',
          fieldList: [
            {
              type: '',
              icon: '',
              displayName: '',
              options: {},
            }
          ]
        },
        detail: [
          {
            entityName: '',
            entityLabel: '',
            fieldList: [
              {
                type: '',
                icon: '',
                displayName: '',
                options: {},
              }
            ],

          }
        ]
      },

      formTemplates: formTemplates,
      // ftImages: [
      //   {imgUrl: ftImg1},
      //   {imgUrl: ftImg2},
      //   {imgUrl: ftImg3},
      //   {imgUrl: ftImg4},
      //   {imgUrl: ftImg5},
      //   {imgUrl: ftImg6},
      //   {imgUrl: ftImg7},
      //   {imgUrl: ftImg8},
      // ]
    }
  },
  computed: {
    showComponentLib() {
      if (this.designerConfig['componentLib'] === undefined) {
        return true
      }

      return !!this.designerConfig['componentLib']
    },

    showFormTemplates() {
      if (this.designerConfig['formTemplates'] === undefined) {
        return true
      }

      return !!this.designerConfig['formTemplates']
    },

    showChartLib() {
      if (this.designerConfig['chartLib'] === undefined) {
        return false
      }

      return !!this.designerConfig['chartLib']
    },

    showMetadataLib() {
      if (this.designerConfig['metadataLib'] === undefined) {
        return false
      }

      return !!this.designerConfig['metadataLib']
    },

  },
  created() {
    if (!!this.designerConfig['chartLib']) {
      this.firstTab = 'chartLib'
    }

    if (!!this.designerConfig['metadataLib']) {
      this.firstTab = 'metadataLib'
    }

    this.loadWidgets()
  },
  mounted() {
    //
  },
  methods: {
    getMetaFieldLabel(widget) {
      const dName = widget.displayName
      return dName.substring(dName.indexOf('.') + 1, dName.length)
    },

    getWidgetLabel(widget) {
      if (!!widget.alias) {  //优先显示组件别名
        return this.i18n2t(`designer.widgetLabel.${widget.alias}`, `extension.widgetLabel.${widget.alias}`)
      }

      return this.i18n2t(`designer.widgetLabel.${widget.type}`, `extension.widgetLabel.${widget.type}`)
    },

    isBanned(wName) {
      return this.getBannedWidgets().indexOf(wName) > -1
    },

    getFTTitle(ft) {
      const langName = getLocale()
      if (!!ft.i18n && !!ft.i18n[langName]) {
        return ft.i18n[langName].title || ft.title
      } else {
        return ft.title
      }
    },

    loadWidgets() {
      this.containers = CONS.map(con => {
        return {
          key: generateId(),
          ...con,
          displayName: this.i18n2t(`designer.widgetLabel.${con.type}`, `extension.widgetLabel.${con.type}`)
        }
      }).filter(con => {
        return !con.internal && !this.isBanned(con.type)
      })

      this.commonContainers = this.containers.filter(con => !!con.commonFlag)

      this.basicFields = BFS.map(fld => {
        return {
          key: generateId(),
          ...fld,
          displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
        }
      }).filter(fld => {
        return !this.isBanned(fld.type)
      })

      this.advancedFields = AFS.map(fld => {
        return {
          key: generateId(),
          ...fld,
          displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
        }
      }).filter(fld => {
        return !this.isBanned(fld.type)
      })

      this.customFields = CFS.map(fld => {
        return {
          key: generateId(),
          ...fld,
          displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
        }
      }).filter(fld => {
        return !this.isBanned(fld.type)
      })

      this.chartContainers = CHART_CONS.map(con => {
        return {
          key: generateId(),
          ...con,
          displayName: this.i18n2t(`designer.widgetLabel.${con.type}`, `extension.widgetLabel.${con.type}`)
        }
      }).filter(con => {
        return !con.internal && !this.isBanned(con.type)
      })

      this.chartWidgets = CWS.map(wgt => {
        return {
          key: generateId(),
          ...wgt,
          displayName: this.i18n2t(`designer.widgetLabel.${wgt.type}`, `extension.widgetLabel.${wgt.type}`)
        }
      }).filter(wgt => {
        return !this.isBanned(wgt.type)
      })
    },

    handleContainerWidgetClone(origin) {
      return this.designer.copyNewContainerWidget(origin)
    },

    handleFieldWidgetClone(origin) {
      return this.designer.copyNewFieldWidget(origin)
    },

    /* draggable组件的move钩子是在内部子组件被拖放到其他draggable组件时触发！！ */
    checkContainerMove(evt) {
      return this.designer.checkWidgetMove(evt)
    },

    /* draggable组件的move钩子是在内部子组件被拖放到其他draggable组件时触发！！ */
    checkFieldMove(evt) {
      console.log('checkFieldMove');
      return this.designer.checkFieldMove(evt)
    },

    onContainerDragEnd(evt) {
      //console.log('Drag end of container: ')
      //console.log(evt)
    },

    addContainerByDbClick(container) {
      this.designer.addContainerByDbClick(container)
    },

    addFieldByDbClick(widget) {
      this.designer.addFieldByDbClick(widget)
    },

    addChartContainerByDbClick(container) {
      this.designer.addChartContainerByDbClick(container)
    },

    addChartByDbClick(chart) {
      this.designer.addChartByDbClick(chart)
    },

    loadFormTemplate(jsonUrl, jsonStr) {
      this.$confirm(this.i18nt('designer.hint.loadFormTemplateHint'), this.i18nt('render.hint.prompt'), {
        confirmButtonText: this.i18nt('render.hint.confirm'),
        cancelButtonText: this.i18nt('render.hint.cancel')
      }).then(() => {
        if (!!jsonStr) {
          this.designer.loadFormJson(JSON.parse(jsonStr))
          this.$message.success(this.i18nt('designer.hint.loadFormTemplateSuccess'))
          return
        }

        axios.get(jsonUrl).then(res => {
          let modifiedFlag = false
          if (typeof res.data === 'string') {
            modifiedFlag = this.designer.loadFormJson(JSON.parse(res.data))
          } else if (res.data.constructor === Object) {
            modifiedFlag = this.designer.loadFormJson(res.data)
          }
          if (modifiedFlag) {
            this.designer.emitHistoryChange()
          }

          this.$message.success(this.i18nt('designer.hint.loadFormTemplateSuccess'))
        }).catch(error => {
          this.$message.error(this.i18nt('designer.hint.loadFormTemplateFailed') + ':' + error)
        })
      }).catch(error => {
        console.error(error)
      })
    },

    setMetaFields(metaFields) {
      this.metaFields = metaFields
    }

  }

}
</script>

<style lang="scss" scoped>
.color-svg-icon {
  -webkit-font-smoothing: antialiased;
  color: #7c7d82;
}

.side-scroll-bar {
  :deep(.ep-scrollbar__wrap) {
    overflow-x: hidden;
  }
}

div.panel-container {
  padding-bottom: 10px;
}

.no-bottom-margin :deep(.ep-tabs__header) {
  margin-bottom: 0;
}

.indent-left-margin {
  :deep(.ep-tabs__nav) {
    margin-left: 20px;
  }
}

.ep-collapse-item :deep(ul) > li {
  list-style: none;
}

.widget-collapse {
  border-top-width: 0;

  :deep(.ep-collapse-item__header) {
    margin-left: 8px;
    font-style: italic;
    font-weight: bold;
  }

  :deep(.ep-collapse-item__content) {
    padding-bottom: 6px;

    ul {
      padding-left: 10px; /* 重置IE11默认样式 */
      margin: 0; /* 重置IE11默认样式 */
      margin-block-start: 0;
      margin-block-end: 0.25em;
      padding-inline-start: 10px;

      &:after {
        content: "";
        display: block;
        clear: both;
      }

      .container-widget-item, .field-widget-item, .chart-container-widget-item, .chart-widget-item {
        //text-align: center; // 居中显示不太美观
        display: inline-block;
        height: 32px;
        line-height: 32px;
        width: 98px;
        float: left;
        margin: 2px 6px 6px 0;
        cursor: move;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        background: #fff;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
        padding: 0 8px;
      }

      .container-widget-item:hover, .field-widget-item:hover, .chart-container-widget-item:hover, .chart-widget-item:hover {
        background: #F1F2F3;
        border-color: var(--ep-color-primary);

        .color-svg-icon {
          color: var(--ep-color-primary);
        }
      }

      .chart-container-widget-item, .chart-widget-item {
        cursor: default !important;
      }

      .drag-handler {
        position: absolute;
        top: 0;
        left: 160px;
        background-color: #dddddd;
        border-radius: 5px;
        padding-right: 5px;
        font-size: 11px;
        color: #666666;
      }
    }
  }
}

.ep-card.ft-card {
  border: 1px solid #8896B3;
}

.ft-card {
  margin-bottom: 10px;

  .bottom {
    margin-top: 10px;
    line-height: 12px;
  }

  /*
  .image-zoom {
    height: 500px;
    width: 620px
  }
  */

  .ft-title {
    font-size: 13px;
    font-weight: bold;
  }

  .right-button {
    padding: 0;
    float: right;
  }

  .clear-fix:before, .clear-fix:after {
    display: table;
    content: "";
  }

  .clear-fix:after {
    clear: both;
  }
}
</style>
<style lang="scss">
.image-popover {
  width: 750px !important;
}

</style>
